package com.example.api.service.impl;

import com.alibaba.fastjson2.JSON;
import com.example.api.config.DeepseekProperties;
import com.example.api.service.DeepseekService;
import com.example.common.model.ChatRequest;
import com.example.common.model.ChatResponse;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class DeepseekServiceImpl implements DeepseekService {

    @Autowired
    private DeepseekProperties properties;

    private final OkHttpClient client = new OkHttpClient();

    @Override
    public ChatResponse chat(ChatRequest request) {
        DeepseekProperties.ProviderConfig config;
        if ("tencent".equals(request.getProvider())) {
            config = properties.getTencent();
        } else if ("alibaba".equals(request.getProvider())) {
            config = properties.getAlibaba();
        } else {
            throw new IllegalArgumentException("Unsupported provider: " + request.getProvider());
        }

        try {
            String response = callApi(config, request.getMessage());
            return createResponse(request.getProvider(), response);
        } catch (Exception e) {
            log.error("Chat API call failed", e);
            throw new RuntimeException("Failed to process chat request", e);
        }
    }

    private String callApi(DeepseekProperties.ProviderConfig config, String message) throws IOException {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "deepseek-r1");
        requestBody.put("messages", new Object[]{
            new HashMap<String, String>() {{
                put("role", "user");
                put("content", message);
            }}
        });

        RequestBody body = RequestBody.create(
            JSON.toJSONString(requestBody),
            MediaType.parse("application/json")
        );

        Request request = new Request.Builder()
            .url(config.getEndpoint())
            .addHeader("Authorization", "Bearer " + config.getApiKey())
            .post(body)
            .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected response " + response);
            }
            return response.body().string();
        }
    }

    private ChatResponse createResponse(String provider, String apiResponse) {
        ChatResponse response = new ChatResponse();
        response.setProvider(provider);
        response.setMessage(extractMessageFromResponse(apiResponse));
        response.setTimestamp(System.currentTimeMillis());
        return response;
    }

    private String extractMessageFromResponse(String apiResponse) {
        // 这里需要根据实际的 API 响应格式进行解析
        // 这是一个示例实现
        try {
            Map<String, Object> response = JSON.parseObject(apiResponse);
            return response.getOrDefault("content", "").toString();
        } catch (Exception e) {
            log.error("Failed to parse API response", e);
            return "Failed to parse response";
        }
    }
} 